package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.SumItem;
import cc.mrbird.febs.buss.service.ISumItemService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.buss.entity.HallItem;
import cc.mrbird.febs.buss.service.IHallItemService;
import cc.mrbird.febs.system.entity.User;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2020-04-24 09:00:57
 */
@Slf4j
@Validated
@Controller
public class HallItemController extends BaseController {

    @Autowired
    private IHallItemService hallItemService;

    @Autowired
    private ISumItemService sumItemService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallItem")
    public String hallItemIndex(){
        return FebsUtil.view("hallItem/hallItem");
    }

    @GetMapping("hallItem")
    @ResponseBody
    public FebsResponse getAllHallItems(HttpServletRequest req) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        User user=this.getCurrentUser();
        map.put("depart",user.getDeptId()+"");
        return new FebsResponse().success().data(hallItemService.findHallItemByMap(map));
    }

    @GetMapping("hallItem/list")
    @ResponseBody
    public FebsResponse hallItemList(QueryRequest request, HttpServletRequest req, HallItem hallItem) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.hallItemService.findHallItemDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallItem/add")
    public String goHallItemAdd(HttpServletRequest req) {
        List<SumItem> list=sumItemService.list();
        req.setAttribute("list",list);
        return FebsUtil.view("hallItem/hallItemAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hallItem/update/{id}")
    public String goHallItemUpdate(@PathVariable String id, Model model) {
        HallItem obj= hallItemService.getById(id);
        model.addAttribute("obj",obj);
        List<SumItem> list=sumItemService.list();
        model.addAttribute("list",list);
        return FebsUtil.view("hallItem/hallItemUpdate");
    }

    @ControllerEndpoint(operation = "新增HallItem", exceptionMessage = "新增HallItem失败")
    @PostMapping("hallItem")
    @ResponseBody
    public FebsResponse addHallItem(@Valid HallItem hallItem) {
        this.hallItemService.createHallItem(hallItem);
        return new FebsResponse().success();
    }

    @GetMapping("hallItem/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteHallItem( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.hallItemService.deleteHallItem(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改HallItem", exceptionMessage = "修改HallItem失败")
    @PostMapping("hallItem/update")
    @ResponseBody
    public FebsResponse updateHallItem(HallItem hallItem) {
        this.hallItemService.updateHallItem(hallItem);
        return new FebsResponse().success();
    }

    @PostMapping(value = "hallItem/fileUpload")
    @ResponseBody
    public FebsResponse fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);  // 后缀名
        InputStream inputstream=null;
        try {
            inputstream=new ByteArrayInputStream(file.getBytes());
            Workbook book = null;
            if ("xls".equals(suffixName)) {
                book = new HSSFWorkbook(inputstream);
            } else{
                book = new XSSFWorkbook(OPCPackage.open(inputstream));
            }
            for(int k=0;k<book.getNumberOfSheets();k++){
                Sheet sheet=book.getSheetAt(k);
                for(int i=1;i<=sheet.getLastRowNum();i++){
                    Row row=sheet.getRow(i);
                    if(row!=null){
                        this.hallItemService.addItemByRow(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new FebsResponse().success();
    }
}
